package net.airtheva.uniqueTask4.lyricLoader;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import net.airtheva.uniqueTask4.Utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class GecimeLyricLoader implements ILyricLoader {

	public static final String TAG = "GecimeLyricLoader";
	
	String mArtist;
	String mTitle;
	
	public GecimeLyricLoader(String artist, String title) {
		// TODO Auto-generated constructor stub
		
		mArtist = artist;
		mTitle = title;
		
	}
	
	@Override
	public String GetLyric() {
		// TODO Auto-generated method stub
		
		try {
			HttpGet hg = new HttpGet("http://geci.me/api/lyric/" + mTitle);
			
			DefaultHttpClient dhc = new DefaultHttpClient();
			
			HttpResponse hr = dhc.execute(hg);
			
			BufferedReader br = new BufferedReader(new InputStreamReader(hr.getEntity().getContent()));
			
			String s = Utils.ReaderToString(br);
			
			JSONObject j = new JSONObject(s);
			
			if(j.getInt("count") == 0) {
				
				Log.d(TAG, "count == 0");
				return null;
				
			}
			else {
				
				String url = j.getJSONArray("result").getJSONObject(0).getString("lrc");
				
				HttpGet hg0 = new HttpGet(url);
				
				HttpResponse hr0 = dhc.execute(hg0);
				
				BufferedReader br0 = new BufferedReader(new InputStreamReader(hr0.getEntity().getContent()));
				
				String s0 = Utils.ReaderToString(br0);
				
				return s0;
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}

}
